import { fetch } from 'dva';
import React from 'react';
import { message } from 'antd';

var tenantId = localStorage.getItem("tenantId");
tenantId = tenantId == "0" ? "1" : tenantId;
const UploadUtil = {
    actionURL: "/api/UploadFilesAsync",
    imgServ: "/api/GetImageAsync?tenantId=" + tenantId + "&sysRowId=",
    pdfServ: "/api/GetPdfAsync?tenantId=" + tenantId + "&sysRowId=",
    QRCodeServer: "/api/GetQRCode",
    accessToken: 'Bearer ' + localStorage.getItem("access-token"),
    uploadPic: async function (files, objectId, objectName, objectField) {
        let formData = new FormData();
        files.forEach(element => {
            formData.append("files", element.originFileObj);
        });
        formData.append("objectId", objectId);
        formData.append("objectName", objectName);
        formData.append("objectField", objectField);

        var resp = {};
        await fetch(this.actionURL, {
            method: 'POST',
            headers: {
                'Authorization': this.accessToken,
            },
            body: formData,
        }).then((response) => response.json())
            .then((responseData) => {
                resp = responseData;
            }).catch((err) => {
                message.error("图片上传失败");
            });
        if (resp && resp.success) {
            return resp.result;
        }
        else {
            return "";
        }
    },
    getBase64: function (img, callback) {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result));
        reader.readAsDataURL(img);
    },
    beforeUpload: function (file) {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('仅限于 JPG/PNG 文件!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('文件大小不得大于 2MB!');
        }
        return isJpgOrPng && isLt2M;
    },
    checkExcel: function (file) {
        const isAllow = file.type === 'application/vnd.ms-excel';
        if (!isAllow) {
            message.error('仅限于 Excel 文件!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('文件大小不得大于 2MB!');
        }
        return isAllow && isLt2M;
    },
    checkPdf: function (file) {
        const isAllow = file.type === 'application/pdf';
        if (!isAllow) {
            message.error('仅限于 PDF 文件!');
            return false;
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('文件大小不得大于 2MB!');
            return false;
        }
        return true;
    }
}

export default UploadUtil;